package com.baizhi.controller;

import com.baizhi.common.Constant;
import com.baizhi.entity.Book;
import com.baizhi.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping("selectBooks")
    @ResponseBody
    public Map selectBooks(String bookName){
        Map map = new HashMap();
        List<Book> books = bookService.selectBook(bookName);
        map.put("list",books);
        return map;
    }

    @RequestMapping("upload")
    @ResponseBody
    public Map upload(MultipartFile file){
        Map map = new HashMap();
        String fileName = UUID.randomUUID().toString()+file.getOriginalFilename();
        try {
            file.transferTo(new File(Constant.IMG_LOCATION,fileName));
            map.put("fileName",fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("addBook")
    @ResponseBody
    public Map addBook(Book book){
        Map map = new HashMap();
        bookService.insertBook(book);
        map.put("flag",true);
        return map;
    }
    @RequestMapping("updateBook")
    @ResponseBody
    public Map updateBook(Book book){
        Map map = new HashMap();
        bookService.updateBook(book);
        map.put("flag",true);
        return map;
    }

    @RequestMapping("removeBook")
    @ResponseBody
    public Map removeBook(Integer id){
        Map map = new HashMap();
        bookService.deleteBook(id);
        map.put("flag",true);
        return map;
    }
    @RequestMapping("getOneBook")
    @ResponseBody
    public Map getOneBook(Integer id){
        Map map = new HashMap();
        Book book = bookService.selectOneBook(id);
        map.put("book",book);
        return map;
    }


}
